﻿using ERPSystem.Common.Domains.UserCommon;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using ERPSystem.Enum.CommonErrorCodes;
using MediatR;

namespace RBACWrite.API.Command.Roless
{
    public class RolesListHandler : IRequestHandler<RolesListCommon, ResultPage<Roles>>
    {
        private readonly IBaseRepository<Roles> rolesRep;
        /// <summary>
        /// 角色列表
        /// </summary>
        /// <param name="rolesRep"></param>
        public RolesListHandler(IBaseRepository<Roles> rolesRep)
        {
            this.rolesRep = rolesRep;
        }
        /// <summary>
        /// 角色列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ResultPage<Roles>> Handle(RolesListCommon request, CancellationToken cancellationToken)
        {
            var result = new ResultPage<Roles>() { Code = (int)CommonErrorCode.Search};
            try
            {
                var list = await (await rolesRep.GetAll()).ToListAsync();
                if (!string.IsNullOrEmpty(request.RoleName))
                {
                    list = list.Where(c => c.RoleName == request.RoleName).ToList();
                }
                result.TotalCount = list.Count();
                result.PageCount = (int)Math.Ceiling(list.Count() / (double)request.pageSize);
                list = list.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();

                result.Code = (int)CommonErrorCode.Success;
                result.Data = list;
                result.Msg = "查询成功";
            }
            catch (Exception)
            {
                result.Msg = "查询失败";
                throw;
            }

            return result;
        }
    }
}
